/* 
* Copyright (C) 2005, 2006 Liu Di <liudidi@gmail.com> 
*
* Copyright (C) 2007 Wei Lian <lianwei3@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "header.h"
#include "mainwindow.h"
#include "sound.h"
#include "config.h"
#include "loadsave.h"
#include "channel.h"
#include "menubar.h"
#include "tabwidget.h"
#include "mystatusbar.h"
#include "mylistitem.h"
#include "pageplay.h"
#include "record.h"


MainWindow::MainWindow (QWidget * parent, const char *name):
QVBox (parent, name)
{
    //menubar
    menubar = new MenuBar (this);

    ///channel row
    QHBox *hbox = new QHBox (this);
    ///button channel
    buttonchannel = new QToolButton (hbox);
    buttonchannel->setAutoRaise (true);
    buttonchannel->setUsesTextLabel (true);
    buttonchannel->setToggleButton (TRUE);
    buttonchannel->setTextLabel (tr ("Channel"));
    ///button expand
    buttonexpand = new QToolButton (hbox);
    buttonexpand->setTextLabel (tr ("Expand"));
    buttonexpand->setAutoRaise (true);
    buttonexpand->setUsesTextLabel (true);
    connect (buttonexpand, SIGNAL (clicked ()), this, SLOT (onButtonExpandClicked ()));
    ///edit search
    editsearch = new QLineEdit (hbox);
    editsearch->setFocus ();
    connect (editsearch, SIGNAL (returnPressed ()), this, SLOT (onButtonSearchClicked ()));
    ///button search
    buttonsearch = new QToolButton (hbox);
    buttonsearch->setTextLabel (tr ("Search"));
    buttonsearch->setAutoRaise (true);
    buttonsearch->setUsesTextLabel (true);
    connect (buttonsearch, SIGNAL (clicked ()), this, SLOT (onButtonSearchClicked ()));
    ///sound slider
    sound = new Sound (this);
    slidersound = new QSlider (0, 100, 5, sound->volume (), QSlider::Horizontal, hbox);
    slidersound->setFixedWidth (60);
    connect (slidersound, SIGNAL (valueChanged (int)), sound, SLOT (volume (int)));
    ///timer for adjusting sound slider
    QTimer *timer = new QTimer (this);
    connect (timer, SIGNAL (timeout ()), this, SLOT (timerDone ()));
    timer->start (1000, FALSE);


    /////vboxconfig
    vboxconfig = new Config (this);

    ///row channel list
    channel = new Channel (this);
    connect (buttonchannel, SIGNAL (toggled (bool)), channel,
	     SLOT (onButtonChannelToggled (bool)));


    ///row tab widget
    tabwidget = new TabWidget (this);

    ///row status bar
    statusbar = new MyStatusBar (this);

    ////load and save
    loadsave = new LoadSave (this);
}


MainWindow::~MainWindow ()
{
    delete loadsave;
    ///save width and height
    if (!isMaximized ()) {
	QSettings settings;
	settings.writeEntry ("/qsopcast/width", size ().width ());
	settings.writeEntry ("/qsopcast/height", size ().height ());
    }
}


void
MainWindow::timerDone ()
{
    ///sound
    int value = sound->volume ();
    if (slidersound->value () != value)
	slidersound->setValue (value);
}


void
MainWindow::onButtonExpandClicked ()
{
    ///test if there are any closed items
    bool flagClose = false;
    QListViewItem *item = channel->firstChild ();
    while (item) {
	if (!item->isOpen ()) {
	    flagClose = true;
	    break;
	}
	item = item->nextSibling ();
    }
    ///set open or close according to flagClose
    item = channel->firstChild ();
    while (item) {
	if (flagClose)
	    item->setOpen (TRUE);
	else
	    item->setOpen (FALSE);
	item = item->nextSibling ();
    }
}


bool
MainWindow::onButtonSearchClicked ()
{
    ///no channel list or no input text
    if (channel->currentItem () == 0 || editsearch->text ().isEmpty ())
	return false;

    ///test whether input text is URL, if so, normalize it
    QString strquery (editsearch->text ());
    bool flagURL;
    int startpos = strquery.find (vboxconfig->editchannelheader->text ());
    ///not a valid URL
    if (startpos == -1)
	flagURL = false;
    else {
	flagURL = true;
	///normalize URL
	strquery = strquery.mid (startpos);
	strquery = strquery.mid (0, strquery.find (" "));
    }

    ////
    bool flagfirst = TRUE;
    QListViewItem *item, *childitem, *focusitem = 0;
    ////set initial value for item and childitem
    if (channel->currentItem ()->depth () == 0) {
	item = channel->currentItem ();
	childitem = item->firstChild ();
    } else {
	childitem = channel->currentItem ();
	item = childitem->parent ();
	childitem = childitem->nextSibling ();
    }
    /////////find focus
    while (1) {
	while (childitem) {
	    if (childitem->isEnabled () &&
		((!flagURL && childitem->text (NAME_COLUMN).contains (strquery, false))
		 || (flagURL && childitem->text (URL_COLUMN) == strquery))) {
		channel->setCurrentItem (childitem);
		focusitem = childitem;
		flagfirst = FALSE;
		goto EXIT;
	    }
	    childitem = childitem->nextSibling ();
	}
	item = item->nextSibling ();
	if (!item)
	    break;
	childitem = item->firstChild ();
    }
  EXIT:;
    ////set color and find first focus if having failed finding focus so far
    item = channel->firstChild ();
    while (item) {
	bool flag = FALSE;
	childitem = item->firstChild ();
	while (childitem) {
	    if (childitem->isEnabled () &&
		((!flagURL && childitem->text (NAME_COLUMN).contains (strquery, false))
		 || (flagURL && childitem->text (URL_COLUMN) == strquery))) {
		static_cast < MyListItem * >(childitem)->bcolor = Qt::yellow;
		childitem->repaint ();

		flag = TRUE;
		if (flagfirst == TRUE) {
		    channel->setCurrentItem (childitem);
		    focusitem = childitem;
		    flagfirst = FALSE;
		}
	    } else {
		static_cast < MyListItem * >(childitem)->bcolor = Qt::white;
		childitem->repaint ();
	    }
	    childitem = childitem->nextSibling ();
	}

	if (flag) {
	    item->setOpen (TRUE);
	} else {
	    item->setOpen (FALSE);
	}

	item = item->nextSibling ();
    }

//////////////////scroll to the first found item
    if (focusitem == 0) {
	channel->setCurrentItem (channel->firstChild ());
	channel->clearSelection ();
	return false;
    }

    int value = channel->itemPos (focusitem) - channel->height () / 2;
    channel->verticalScrollBar ()->setValue (value);
    return true;
}


void
MainWindow::keyPressEvent (QKeyEvent * e)
{
    if (e->key () == Qt::Key_Escape) {
	editsearch->setFocus ();
	editsearch->clear ();
    } else
	QVBox::keyPressEvent (e);
}
